<template>
  <div>
    <el-dialog v-model="parentAsinDialog.visible.value" :title="parentAsinDialog.title.value" width="80%" append-to-body>
      <el-row :gutter="20">
        <el-col :lg="20" :xs="24">
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                  <el-form-item label="FNSKU" prop="fnSku">
                    <el-input v-model="queryParams.fnSku" placeholder="请输入fnSku" clearable />
                  </el-form-item>
                  <el-form-item label="产品名称" prop="productName">
                    <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable />
                  </el-form-item>
                  <el-form-item label="asin" prop="asin">
                    <el-input v-model="queryParams.asin" placeholder="请输入asin" clearable />
                  </el-form-item>
                  <el-form-item label="第三方SKU" prop="localSku">
                    <el-input v-model="queryParams.localSku" placeholder="请输入第三方SKU" clearable />
                  </el-form-item>
                  <el-form-item label="第三方产品名称" prop="localName">
                    <el-input v-model="queryParams.localName" placeholder="请输入第三方产品名称" clearable />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="() => resetQuery()">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <el-card shadow="hover">
            <template v-if="prop.multiple" #header>
              <el-tag v-for="product in selectProductList" :key="product.asin" closable style="margin: 2px" @close="handleCloseTag(product)">
                {{ product.asin }}
              </el-tag>
            </template>

            <vxe-table
              ref="tableRef"
              height="400px"
              border
              show-overflow
              :data="productList"
              :loading="loading"
              :row-config="{ keyField: 'asin', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column key="asin" title="父ASIN" align="center" field="asin" />
              <vxe-column key="productName" title="产品名称" align="center" field="productName" />
              <vxe-column key="fnSku" title="fnSku" align="center" field="fnSku" />
              <vxe-column key="localSku" title="第三方SKU" align="center" field="localSku" />
              <vxe-column key="localName" title="第三方产品名称" align="center" field="localName" width="120" />
            </vxe-table>

            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="pageList"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { pageProduct } from '@/api/product/product';
import { ProductQuery, ProductVO } from '@/api/product/product/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';

interface PropType {
  modelValue?: ProductVO[] | ProductVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[];
  productType: string | number;
}

const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined,
  productType: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productList = ref<ProductVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const selectProductList = ref<ProductVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<ProductVO>>();

const parentAsinDialog = useDialog({
  title: '父ASIN选择'
});

const queryParams = ref<ProductQuery>({
  pageNum: 1,
  pageSize: 10,
  fnSku: '',
  productName: '',
  asin: '',
  localSku: '',
  localName: '',
  productType: ''
});

const defaultProductAsinList = computed(() => computedIds(prop.data));

/** 根据名称筛选部门树 */
watchEffect(() => {}, {
  flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
});

const confirm = () => {
  emit('update:modelValue', selectProductList.value);
  emit('confirmCallBack', selectProductList.value);
  parentAsinDialog.closeDialog();
};

const computedIds = (data) => {
  if (data instanceof Array) {
    return [...data];
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [data];
  } else {
    console.warn('<UserSelect> The data type of data should be array or string or number, but I received other');
    return [];
  }
};

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.productType = prop.productType;
  const res = await pageProduct(queryParams.value);
  loading.value = false;
  productList.value = res.rows;
  total.value = res.total;
};

const pageList = async () => {
  await getList();
  const users = productList.value.filter((item) => {
    return selectProductList.value.some((product) => product.asin === item.asin);
  });
  await tableRef.value.setCheckboxRow(users, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectProductList.value, false);
    selectProductList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectProductList.value.push(row);
  } else {
    selectProductList.value = selectProductList.value.filter((item) => {
      return item.asin !== row.asin;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = productList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectProductList.value.some((item) => item.asin === row.asin)) {
        selectProductList.value.push(row);
      }
    });
  } else {
    selectProductList.value = selectProductList.value.filter((item) => {
      return !rows.some((row) => row.asin === item.asin);
    });
  }
};

const handleCloseTag = (productVO: ProductVO) => {
  const asin = productVO.asin;
  // 使用split删除用户
  const index = selectProductList.value.findIndex((item) => item.asin === asin);
  const rows = selectProductList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectProductList.value.splice(index, 1);
};

// const initSelectUser = async () => {
//   if (defaultProductAsinList.value.length > 0) {
//     const { data } = await api.optionSelect(defaultProductAsinList.value);
//     selectProductList.value = data;
//     const asins = productList.value.filter((item) => {
//       return defaultProductAsinList.value.includes(String(item.asin));
//     });
//     await nextTick(() => {
//       tableRef.value.setCheckboxRow(asins, true);
//     });
//   }
// };
const close = () => {
  parentAsinDialog.closeDialog();
};

watch(
  () => parentAsinDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      // await initProduct();
    } else {
      await tableRef.value.clearCheckboxReserve();
      await tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectProductList.value = [];
    }
  }
);

defineExpose({
  open: parentAsinDialog.openDialog,
  close: parentAsinDialog.closeDialog
});
</script>

<style lang="scss" scoped></style>
